﻿angular.module('paperless').controller('transactionsController', function ($scope, Restangular, ngTableParams) {
    'use strict';

    $scope.filters = {};

    $scope.quickSearch = function () {
        $scope.tableParams.reload();
    }

    $scope.tableParams = new ngTableParams({
        page: 1,
        count: 3
    }, {
        counts: [3, 5, 7],
        getData: function ($defer, params) {
            var sorting = params.sorting(),
                ascList,
                descList;

            if (sorting) {
                ascList = [];
                descList = [];

                angular.forEach(sorting, function (item, index) {
                    if (item == 'asc') {
                        ascList.push(index);
                    }

                    if (item == 'desc') {
                        descList.push(index);
                    }
                });
            }

            Restangular.all('transaction')
                .getList({
                    page: params.page(),
                    count: params.count(),
                    ascendings: ascList.length ? ascList.join(',') : undefined,
                    descendings: descList.length ? descList.join(',') : undefined,
                    name: $scope.filters.transactionName
                }).then(function (transactions) {
                    params.total(transactions.total);

                    angular.forEach(transactions, function (transaction) {
                        transaction.listingAgents = [];
                        transaction.sellingAgents = [];

                        angular.forEach(transaction.assignAgents, function (agent) {
                            if (agent.listing) {
                                transaction.listingAgents.push(agent.name);
                            }
                            if (agent.selling) {
                                transaction.sellingAgents.push(agent.name);
                            }
                        });
                    });

                    $defer.resolve(transactions);
                });
        }
    });
});